package sql;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.util.Properties;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;


public class CacheHandlerTest {
	
	@Before
	public void PropertiesStringSearchTest() throws FileNotFoundException, IOException, ClassNotFoundException, SQLException {
		
		// reading the properties
		Properties p = new Properties();
		p.load(new FileInputStream("config"));
		
		// checking if the cache handler found the properties
		CacheHandler.createCache(p);
	}
	
	@After
	public void clearDB() throws FileNotFoundException, IOException, ClassNotFoundException, SQLException {
		
		// reading the properties
		Properties p = new Properties();
		p.load(new FileInputStream("config"));
		
		CacheHandler.clear(p);
	}
	
	/**
	 * Testing the insertion of the record
	 * creating: url,headers,content,lastmodified
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 * @throws SQLException 
	 * @throws ClassNotFoundException 
	 */
	@Test
	public void insertRecordTest() throws FileNotFoundException, IOException, ClassNotFoundException, SQLException {
		
		// reading the properties
		Properties p = new Properties();
		p.load(new FileInputStream("config"));
		
		// creating a record with an empty content
		URL url = new URL("http://test.com");
		String headers = "GET / HTTP/1.1";
		ByteArrayInputStream null_content = null; 
		
		CacheHandler.insertRecord(url, headers, null_content, "0", p);
		
		// creating a record with a content of bytes
		byte [] byte_content =  {1,1,1};
		ByteArrayInputStream char_content = new ByteArrayInputStream(byte_content);

		CacheHandler.insertRecord(url, headers, char_content, "0", p);
		
		CacheHandler.printCacheContent(p); 
	}
	
	@Test
	public void getRecordTest() throws FileNotFoundException, IOException, SQLException, ClassNotFoundException {
		
		// reading the properties
		Properties p = new Properties();
		p.load(new FileInputStream("config"));
		
		insertRecordTest();
		
		// creating a record with an empty content
		URL url = new URL("http://test.com");
		
		ResponseWrapper res = CacheHandler.getRecord(url, p);
		System.out.println(res.getUrl());
		System.out.println(res.getHeaders());
		System.out.println(res.getContent());
		System.out.println(res.getLastmodified());
	}
}
